package com.guaoran.security.demo.config;

import com.guaoran.commons.swagger.ui.IWebSecurityConfigurer;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.web.mappings.MappingsEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @Author gucheng
 * @Description security 配置
 * 2019-07-23 16:23
 */
@Configuration
public class SecurityConfiguration implements IWebSecurityConfigurer {
    // 覆盖了swagger的属性配置
    @SuppressWarnings("deprecation")
    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
        return new InMemoryUserDetailsManager(
                User.withDefaultPasswordEncoder().username("user").password("password")
                        .authorities("ROLE_USER").build(),
                User.withDefaultPasswordEncoder().username("beans").password("beans")
                        .authorities("ROLE_BEANS").build(),
                User.withDefaultPasswordEncoder().username("admin").password("admin")
                        .authorities("ROLE_ACTUATOR", "ROLE_USER").build());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // /actuator/beans 权限认证的角色是 BEANS
                .mvcMatchers("/actuator/beans").hasRole("BEANS")
                // health info 不需要权限认证
                .requestMatchers(EndpointRequest.to("health", "info")).permitAll()
                // 除上面的 beans 需要单独的角色外，health、info 不需要权限外，其他 EndpointRequest 端点请求都是用 ACTUATOR 角色
                .requestMatchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)).hasRole("ACTUATOR")
                // 静态（static 目录）资源不需要权限认证
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                // /foo 路径请求不需要权限认证
                .antMatchers("/foo").permitAll()
                // 除以上配置以外都是用 USER 角色进行权限认证
                .antMatchers("/**").hasRole("USER")
//                .and()
//                // 登录 和 登录失败不需要权限认证
//                .formLogin().loginPage("/login").failureUrl("/login?error").permitAll()
//                .and()
//                .logout().permitAll()
                .and()
                .cors()
                .and()
                .httpBasic();
    }
}
